function getGlobalPathRoot() {
    var strFullPath = window.document.location.href;
    var strPath = window.document.location.pathname;
    var pos = strFullPath.indexOf(strPath);
    var prePath = strFullPath.substring(0, pos);
    var postPath = strPath.substring(0, strPath.substr(1).indexOf('/') + 1);
    return (prePath + postPath);
}

JMap = function () {
    this.clear();
};
JMap.prototype.clear = function () {
    this.data = {};
};
// JMap.prototype.add=function(n,v){ this.data[n] = v };
JMap.prototype.add = function (n, v) {
    if (typeof (v) == "object" && v != null) {
        this.serialize(this.data, n, v);
    }
    this.data[n] = v;
};

JMap.prototype.serialize = function (originObj, name, obj) {
    if (obj.length) {
        var vLength = obj.length;
        for (var i = 0; i < vLength; i++) {
            var index = name + "[" + i + "]";
            if (obj[i] && typeof (obj[i]) == "object") {
                jmap = new JMap();
                jmap.serialize(originObj, index, obj[i]);
            } else {
                originObj[index] = obj[i];
            }
        }
    } else {
        for (var s in obj) {
            if (typeof (obj[s]) == "object") {
                jmap = new JMap();
                jmap.serialize(originObj, s, obj[s]);
            } else {
                originObj[s] = obj[s];
            }
        }
    }
};

JMap.prototype.findValueByName = function (n) {
    return this.data[n];
};
AJAXPacket = function (url, clickObject, text, timeout) {
    this.url = url;
    this.clickObject = clickObject;
    this.data = new JMap();
    this.statusText = text;
    this.guid = "";
    this.timeout = timeout;
};
var core = {};
core.ajax = {
    receivePacket: function (packet) {
    },
    /**
     * 获取AJAXPacket请求结果
     * @param packet 请求参数与路径
     * @param process 回调处理方法
     * @param aysncflag 异步处理标识 true:异步处理 false:同步处理，不传默认true
     * @param showBlock 是否展示蒙层
     * @param packet.timeout 设置超时时间，单位毫秒，默认值为30000（30秒）,为0时不超时
     * 同步处理dynamicLoadpage后的方法将进行等待，服务器处理完成后才进行处理
     * 异步处理在服务端未执行完成，dynamicLoadpage后的方法立即执行，不等待服务器返回
     */
    sendPacket: function (packet, process, aysncflag, showBlock) {
        // 取消默认超时时间为30秒 放宽至一分钟
        var defaultTimeouts = "0";
        if (packet.timeout) {
            defaultTimeouts = packet.timeout;
        }
        if (showBlock == null) {
            showBlock = true;
        }
        if (showBlock) {
            // 调蒙层函数
            loading();
        }
        if (aysncflag == null) {
            aysncflag = true;
        }
        var sendUrl = packet.url;
        var sendData = packet.data.data;
        // 点击按钮不可用
        if (packet.clickObject) {
            $(packet.clickObject).attr("disabled", true);
        }
        $.ajax({
            url: sendUrl,
            data: sendData,
            type: "POST",
            async: aysncflag,
            timeout: defaultTimeouts,
            dataType: "html",
            contentType: "application/x-www-form-urlencoded;charset=UTF-8",
            success: function (data) {
                eval(data);
                process && process(response);
                response = null;
                // 处理成功删除进度条
                if (showBlock) {
                    unLoading();
                }
                // 按钮恢复可用
                if (packet.clickObject) {
                    $(packet.clickObject).removeAttr("disabled");
                }
            },
            error: function (data) {
                if (data.status == "404") {
                    alertMsg.error("文件不存在!");
                } else if (data.status == "500") {
                    var errorJsonStr = data.getResponseHeader("Error-Json");
                    if (errorJsonStr != null || errorJsonStr != "") {
                        var errorJson = eval("(" + errorJsonStr + ")");
                        if (errorJson.code && errorJson.code == "121004") {
                            alertMsg.error("用户未登录或登录失效!");
                            setTimeout(function () {
                                location.href = getGlobalPathRoot() + "/sysuser/login"
                            }, 3000);
                        } else {
                            alertMsg.error("CMS-" + errorJson.code + "服务信息返回错误信息!");
                        }
                    } else {
                        alertMsg.error("CMS-" + errorJson.code + "服务信息返回错误信息!");
                    }
                } else {
                    alertMsg.error("CMS-" + data.status + ":系统错误!");
                }
                if (showBlock) {
                    unLoading();
                }
                // 按钮恢复可用
                if (packet.clickObject) {
                    $(packet.clickObject).removeAttr("disabled");
                }
                if (data.statusText == "timeout") {
                    alertMsg.error("页面加载超时，请重试!");
                    // 清除手工添加的页面蒙层
                    unLoading();
                }
            }
        });
    },

    /**
     * 获取自定义请求结果，可以使页面、json字符串等任意结果
     * @param packet 请求参数与路径
     * @param process 回调处理方法
     * @param aysncflag 异步处理标识 true:异步处理 false:同步处理，不传默认true
     * @param showBlock 是否展示蒙层 默认 true
     * @param packet.timeout 设置超时时间，单位毫秒，默认值为30000（30秒），为0时不超时
     * 同步处理dynamicLoadpage后的方法将进行等待，服务器处理完成后才进行处理
     * 异步处理在服务端未执行完成，dynamicLoadpage后的方法立即执行，不等待服务器返回
     */
    sendPacketHtml: function (packet, process, aysncflag, showBlock) {
        // 取消默认超时时间为30秒 放宽至一分钟
        var defaultTimeouts = "0";
        if (packet.timeout) {
            defaultTimeouts = packet.timeout;
        }
        if (showBlock == null) {
            showBlock = true;
        }
        if (showBlock) {
            loading();
        }
        // 默认展示进度条
        if (aysncflag == null) {
            aysncflag = true;
        }
        var sendUrl = packet.url;
        var sendData = packet.data.data;
        // 点击按钮不可用
        if (packet.clickObject) {
            $(packet.clickObject).attr("disabled", true);
        }
        $.ajax({
            url: sendUrl,
            data: sendData,
            type: "POST",
            async: aysncflag,
            timeout: defaultTimeouts,
            dataType: "html",
            contentType: "application/x-www-form-urlencoded;charset=UTF-8",
            success: function (data) {
                process && process(data);
                if (showBlock) {
                    unLoading();
                }
                // 按钮恢复可用
                if (packet.clickObject) {
                    $(packet.clickObject).removeAttr("disabled");
                }
            },
            error: function (data) {
                if (data.status == "404") {
                    alertMsg.error("文件不存在!");
                } else if (data.status == "500") {
                    var errorJsonStr = data.getResponseHeader("Error-Json");
                    if (errorJsonStr != null || errorJsonStr != "") {
                        var errorJson = eval("(" + errorJsonStr + ")");
                        if (errorJson.code && errorJson.code == "121004") {
                            alertMsg.error("用户未登录或登录失效!");
                            setTimeout(function () {
                                location.href = getGlobalPathRoot() + "/sysuser/login"
                            }, 3000);
                        } else {
                            alertMsg.error("CMS-" + errorJson.code + "服务信息返回错误信息!");
                        }
                    } else {
                        alertMsg.error("CMS-" + errorJson.code + "服务信息返回错误信息!");
                    }
                } else {
                    alertMsg.error("CMS-" + data.status + ":系统错误!");
                }
                if (showBlock) {
                    unLoading();
                }
                // 按钮恢复可用
                if (packet.clickObject) {
                    $(packet.clickObject).removeAttr("disabled");
                }
                if (data.statusText == "timeout") {
                    alertMsg.error("页面加载超时，请重试!");
                    // 清除手工添加的页面蒙层
                    unLoading();
                }
            }
        });
    },
    /**
     * Ajax获取动态页面内容,填充指定控件内容
     * @param packet 请求信息
     * @param id 填充控件ID
     * @param aysncflag 异步处理标识 true:异步处理 false:同步处理，不传默认false
     * @param showBlock 是否展示蒙层 默认展示蒙层
     * 同步处理dynamicLoadpage后的方法将进行等待，服务器处理完成后才进行处理
     * 异步处理在服务端未执行完成，dynamicLoadpage后的方法立即执行，不等待服务器返回
     */
    dynamicLoadpage: function (packet, id, aysncflag, showBlock) {
        core.ajax.sendPacketHtml(packet, function (data) {
            $("#" + id).html(data);
        }, aysncflag, showBlock);
    }
};

/**
 * Created by leon on 2017/2/14.
 */
function jumpPage(pageNo, _divId) {
    var jsonData = $.parseJSON($("#" + _divId + "").find("input[name='queryCondition']").val());
    // var pageSizeNo = $("#" + _divId + "").find("input[name='pageSizeNo']").val();
    var pageSizeNo = $("#" + _divId + "").find("#pageSize").val();
    jsonData.pageSize = pageSizeNo;
    jsonData.pageNo = pageNo;
    var packet = new AJAXPacket(jsonData.reqUrl, this);
    packet.data.data = jsonData;
    core.ajax.sendPacketHtml(packet, function (response) {
        if (response != null) {
            $("#" + _divId).html(response);
        }
    })

}

function jumpPageTo(_divId) {
    var jsonData = $.parseJSON($("#" + _divId + "").find("input[name='queryCondition']").val());
    var pageSizeNo = $("#" + _divId + "").find("#pageSize").val();
    $('#pageSizeNo').val(pageSizeNo);

    var pageNo = $("#" + _divId + "").find("input[name='pageNo']").val();
    jsonData.pageSize = pageSizeNo;
    jsonData.pageNo = pageNo;
    var packet = new AJAXPacket(jsonData.reqUrl, this);
    packet.data.data = jsonData;
    core.ajax.sendPacketHtml(packet, function (response) {
        if (response !== null) {
            $("#" + _divId).html(response);
        }
    })
}

var divId = "pageList";
var formId = "sourceForm";

/**
 * 公共列表查询方法
 * @param _reqUrl 请求地址
 * @param formId 表单ID
 * @param _divId 展示结果DIV展示区域
 */
function queryList(_reqUrl, _formId, _divId) {
    var jsonData;
    if (_divId == null) {
        _divId = divId;
    }
    if (_formId == null) {
        _formId = formId;
    }
    jsonData = $("#" + _formId).serializeArray();// 序列化表单数据
    jsonData.push({
        name: 'divId',
        value: _divId
    });
    jsonData.push({
        name: 'reqUrl',
        value: _reqUrl
    });

    var packet = new AJAXPacket(_reqUrl, this);
    packet.data.data = jsonData;
    core.ajax.sendPacketHtml(packet, function (response) {
        if (response !== null) {
            $("#" + _divId).html(response);
        }
    })
}

function jumpMenu(url, _divId) {
    if (_divId == null) {
        _divId = "pageList";
    }
    if (url == null || url == '') {
        url = getGlobalPathRoot() + '/index';
    }
    var packet = new AJAXPacket(url);
    core.ajax.dynamicLoadpage(packet, _divId);
}

// tip是提示信息，type:'success'是成功信息，'danger'是失败信息,'info'是普通信息,'warning'是警告信息
function ShowTip(tip, type) {
    var $tip = $('#tip');
    $tip.stop(true).prop('class', 'alert alert-' + type).html("<h3>" + tip + "</h3>").css('margin-left', -$tip.outerWidth() / 2).fadeIn(500).delay(1000).fadeOut(500);
}

function ShowMsg(msg) {
    ShowTip(msg, 'info');
}

function ShowSuccess(msg) {
    ShowTip(msg, 'success');
}

function ShowFailure(msg) {
    ShowTip(msg, 'danger');
}

function ShowWarn(msg, $focus, clear) {
    ShowTip(msg, 'warning');
    if ($focus) {
        $focus.focus();
        if (clear) $focus.val('');
    }
    return false;
}

var alertMsg = {
    info: function (msg) {
        ShowTip(msg, 'info');
    },
    correct: function (msg) {
        ShowTip(msg, 'success');
    },
    error: function (msg) {
        // ShowTip(msg, 'danger');
        var $tip = $('#tip');
        var $html = "<h3>" + msg + "</h3><br></button><button type='button' class='btn btn-danger' id='tipCancelBtn'>确 定</button><script>$('#tipCancelBtn').bind('click', function() { var $tip = $('#tip');$tip.stop(true).fadeOut(100); })</script>";
        $tip.stop(true).prop('class', 'alert alert-danger').html($html).css('margin-left', -$tip.outerWidth() / 2).fadeIn(500).delay(5000).fadeOut(500);
    },
    sure: function (msg) {
        // ShowTip(msg, 'danger');
        var $tip = $('#tip');
        var $html = "<h3>" + msg + "</h3><br></button><button type='button' class='btn btn-default' id='tipCancelBtn'>确 定</button><script>$('#tipCancelBtn').bind('click', function() { var $tip = $('#tip');$tip.stop(true).fadeOut(100); })</script>";
        $tip.stop(true).prop('class', 'alert alert-success').html($html).css('margin-left', -$tip.outerWidth() / 2).fadeIn(500);
    },
    warn: function (msg) {
        ShowTip(msg, 'warning');
    },
    confirm: function (msg, option) {
        $.confirm({
            title: msg,
            content: '',
            type: 'red',
            buttons: {
                ok: {
                    text: "OK!",
                    btnClass: 'btn-danger',
                    keys: ['enter'],
                    action: function () {
                        option && option();
                    }
                },
                cancel: function () {

                }
            }
        });
    }
}

// 显示等待效果，从调用页面弹出
function loading() {
    $('body').css("overflow", "hidden");
    $("#cover").show();
}

// 取消ajax等待效果
function unLoading() {
    window.setTimeout("$('body').css('overflow','');$('#cover').hide();",
        100);
}

function area(a) {
    if (!document.getElementById("titleArea")) {
        var instance = new ysdq.RegionSelector('#regionContainer');
        instance.setRegions(a);
    }
}


function checkAll(a) {
    var o = document.getElementsByName(a);
    for (var i = 0; i < o.length; i++) {
        o[i].checked = event.srcElement.checked;
    }
}

function checkFalse(a) {
    var o = document.getElementsByName(a);
    for (var i = 0; i < o.length; i++) {
        if (!event.srcElement.checked) {
            $("#sourceAll").attr('checked', false);
        }
    }
}